import mockGroups from "@/mock/groups.json";
import mockMaterials from "@/mock/materials.json";
import mockOrder from "@/mock/order.json";
import { OrderDetail } from "@/types/bom";
import { exportJson } from "@/utils/export";
import { transformData } from "@/utils/transform";
import { useMount, useRequest } from "ahooks";
import { Button, Card } from "antd";
import { useRef, useState } from "react";
import { FormDescriptions } from "../components/FormDescriptions";

const log = console.log.bind(null, '[page]');

// --- used miniapp api ---
(() => {
  Manycore.Integration.FOP.findOrdersAsync
  Manycore.Integration.FOP.getOrderAsync
  Manycore.Integration.Bom.findMaterialsAsync
  Manycore.Integration.Bom.findGroupsByOrderIdAsync
})
// ---

type OriginData = Parameters<typeof transformData>[0]

export default function IndexPage() {
  const { data: order, loading: orderLoading } = useRequest(async () => {
    const str = await Manycore.Miniapp.getUploadedDataAsync()
    if (!str) {
      return
    }
    const { orderId } = JSON.parse(str)
    const order = await Manycore.Integration.FOP.getOrderAsync(orderId)
    await onConfirm(order)
    return order
  })
  const originDataRef = useRef<OriginData>()
  const [exportData, setExportData] = useState<object>()

  if (process.env.NODE_ENV === 'development') {
    useMount(async () => {
      const originData = { order: mockOrder, materials: mockMaterials, groups: mockGroups }
      // @ts-expect-error
      const result = await onTransformData(originData)
      log('[mock]', 'originData', originData, 'transformData', result)
    })
  }

  async function onTransformData(...params: Parameters<typeof transformData>) {
    const [originData] = params
    originDataRef.current = (originData)
    const result = await transformData(originData)
    setExportData(result)
    return result
  }

  const onConfirm = async (order: OrderDetail) => {
    const { orderId } = order
    const { groups } = await Manycore.Integration.Bom.findGroupsByOrderIdAsync({ orderIds: [orderId] })
    const materials = await Manycore.Integration.Bom.findMaterialsAsync({ orderIds: [orderId] })
    const originData = { order, materials, groups }
    const result = await onTransformData(originData)
    log('[readme=>]', 'originData', originData, 'transformData', result)
  }

  function onExport() {
    const originData = originDataRef.current!
    exportJson(exportData!, originData.order.orderNo)
  }

  return (
    <div className="app">
      <Card size="small" className="border-0">
        <FormDescriptions
          items={[
            { label: '订单编号', children: order?.orderNo },
            { label: '订单名称', children: order?.orderName },
          ]}
        />
        <Button block type="primary" onClick={onExport} disabled={!exportData}>导出数据</Button>
      </Card>
    </div>
  );
}
